<?php

class SiteController extends CController
{
	//public $layout='site';
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image
			// this is used by the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xEBF4FB,
			),
		);
	}
	
	public function filters(){
		return array(
			array('application.filters.LoginFilter -login,to_login,send_sms,chk_lock'),
			array('application.filters.AuthFilter +add_sms,search_sms'),
		);
	}
	
	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
		// renders the view file 'protected/views/site/index.php'
		// using the default layout 'protected/views/layouts/main.php'
		$this->renderPartial('index');
	}

	public function actionMakeReminderPage(){
		//计划单提示
		$criteria=new CDbCriteria();
		$criteria->join='INNER JOIN path ON schedule_list.fk_path_id=path.id
						 INNER JOIN consignor_info as consignor ON schedule_list.fk_consignor_id=consignor.id';
		$criteria->select='schedule_list.id as id,schedule_list.create_time as create_time,consignor.name as consignor_name,
		path.loading_place as deliver_place,path.pod_place as arrival_place';
		$criteria->addCondition('schedule_list.state=0');
		$criteria->order='schedule_list.create_time DESC';
		$criteria->limit=12;
		$schedule_models=Schedule_list::model()->findAll($criteria);
		
		//年审提示
		$sql='select * from (
			  Select tmp.id,trucks.plate_no,tmp.next_verify_date,tmp.kind From 
			  (Select * From annual_verification_info where state=0  Order By next_verify_date Desc) As tmp 
			  inner JOIN trucks on tmp.fk_truck_id=trucks.id and trucks.state=0 
			  Group By tmp.fk_truck_id order by tmp.next_verify_date) AS t where t.next_verify_date<=CURDATE()+15 limit 2';
		$verification_models=Annual_verification::model()->findAllBySql($sql);
		
		//营运证等级鉴定
		$sql='select * from (
			  Select tmp.id,trucks.plate_no,tmp.next_grade_identify_date,tmp.kind From 
			  (Select * From grade_identification where state=0  Order By next_grade_identify_date Desc) As tmp 
			  inner JOIN trucks on tmp.fk_truck_id=trucks.id and trucks.state=0 
			  Group By tmp.fk_truck_id order by tmp.next_grade_identify_date) AS t where t.next_grade_identify_date<=CURDATE()+15 limit 2';
		$grade_models=Grade_identification::model()->findAllBySql($sql);
		
		//营运证强制保养
		$sql='select * from (
			  Select tmp.id,trucks.plate_no,tmp.next_mm_date,tmp.kind From 
			  (Select * From mandatory_maintenance where state=0  Order By next_mm_date Desc) As tmp 
			  inner JOIN trucks on tmp.fk_truck_id=trucks.id and trucks.state=0 
			  Group By tmp.fk_truck_id order by tmp.next_mm_date) AS t where t.next_mm_date<=CURDATE()+15 limit 2';
		$mandatory_models=Mandatory_maintenance::model()->findAllBySql($sql);
		
		//保险
		$sql='select * from (
			  Select tmp.id,tmp.premium_name,trucks.plate_no,tmp.lapsedate,tmp.kind From 
			  (Select * From vehicle_insurance where state=0  Order By lapsedate Desc) As tmp 
			  inner JOIN trucks on tmp.fk_truck_id=trucks.id and trucks.state=0 
			  Group By tmp.fk_truck_id order by tmp.lapsedate) AS t where t.lapsedate<=CURDATE()+15 limit 2';
		$vehicle_models=Vehicle_insurance::model()->findAllBySql($sql);
		
		//待修车辆
		$criteria=new CDbCriteria();
		$criteria->join='INNER JOIN trucks ON truck_to_repair.fk_truck_id=trucks.id and trucks.state=0';
		$criteria->select='truck_to_repair.id,truck_to_repair.create_time,trucks.plate_no,trucks.reg_no,trucks.kind';
		$criteria->addCondition('truck_to_repair.state=0');
		$criteria->order='truck_to_repair.create_time DESC';
		$criteria->limit=2;
		$repair_models=Truck_to_repair::model()->findAll($criteria);
		
		
		$str=$this->renderPartial('reminder',array('schedule_models'=>$schedule_models,'verification_models'=>$verification_models,
							'grade_models'=>$grade_models,'mandatory_models'=>$mandatory_models,'vehicle_models'=>$vehicle_models,
						   'repair_models'=>$repair_models),true);
 		$file_path=Yii::app()->basePath.'/../reminder.html';
		$handle = fopen ($file_path,"w");
 		if (!is_writable ($file_path)){
  			return false;
 		}
 		if (!fwrite ($handle,$str)){
  			return false;
 		} 
		fclose ($handle); //关闭指针
	}

	/**
	 * Displays the login page
	 */
	public function actionLogin()
	{
		$form=new LoginForm;
		// collect user input data
		if(isset($_POST['LoginForm']))
		{
			$form->attributes=$_POST['LoginForm'];
			// validate user input and redirect to previous page if valid
			if($form->validate()){//这个验证包括了在loginform中定义的验证用户名与密码rule 
				$this->redirect(Yii::app()->user->returnUrl);
				//$this->actionIndex();
				//return;
			}
		}
		// display the login form
		$this->render('login',array('form'=>$form));
	}

	
	public function ActionTo_login(){
		$this->render('to_login');
	}
	
	public function ActionTo_close(){
		$this->render('to_close');
	}
	
	/**
	 * Logout the current user and redirect to homepage.
	 */
	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}
	
	public function actionUploadedFiles()
	{
		if (!empty($_FILES)) {
		$tempFile = $_FILES['Filedata']['tmp_name'];
		$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
		$fileParts  = pathinfo($_FILES['Filedata']['name']);
		$ext='.'.$fileParts['extension'];
		$fileName=date('YmdGis').mt_rand(10,99).$ext;
		$targetFile =  str_replace('//','/',$targetPath) . $fileName;
		
		
		// $fileTypes  = str_replace('*.','',$_REQUEST['fileext']);
		// $fileTypes  = str_replace(';','|',$fileTypes);
		// $typesArray = split('\|',$fileTypes);
		
	
		// if (in_array($fileParts['extension'],$typesArray)) {
		// Uncomment the following line if you want to make the directory if it doesn't exist
		// mkdir(str_replace('//','/',$targetPath), 0755, true);
		
		move_uploaded_file($tempFile,$targetFile);
		chmod($targetFile,0664);
		echo $fileName;
		}
	}
	
	public function actionChk_lock(){
		$shid=shmop_open(1, "a", 0, 0);
		echo 'app_lock:'.shmop_read($shid, 0, 1); 
		shmop_close($shid); 
		
		$shid=shmop_open(2, "a", 0, 0);
		echo ' app_lock_time:'.shmop_read($shid, 0, 10); 
		shmop_close($shid); 
	}
	
	public function actionSend_sms(){
		$criteria=new CDbCriteria();
		$criteria->addCondition('state=0');
		$criteria->addCondition('sent=0');
		$criteria->order='create_time';
		$models=Sms_queue::model()->findAll($criteria);
		if(empty($models)) {echo 'no msg!';return;}
		
		set_time_limit(0); 
		$serial = new phpSerial;
		$succ=0;
		try{
			$serial->setSpeed(Yii::app()->params['sms_speed']);
			$serial->deviceSet(Yii::app()->params['sms_serial_port']);
			if(!$serial->deviceOpen()) {echo 'open port error!';return;}
			if(!$serial->checkCSQ()) {echo 'bad CSQ!'; return;}
			echo 'total:'.count($models)."\n";
			foreach($models as $n=>$model){
				echo 'send msg'.($n+1)."...";
				$tran=$model->getDbConnection()->beginTransaction();
				try{
					$p=$serial->sendMess('86'.$model->mobile_no,$model->msg);
					$model->sent=1;
					$model->send_time=date('Y-m-d G:i:s');
					$model->save(false);
					if($p){
						$succ++;
						echo "ok!\n";
						$tran->commit();
					} 
					else{ 
						echo "fail\n";
						$tran->rollBack();
					}
				}catch(Exception $e){
					echo 'fail';
					$tran->rollBack();
				}
			}
			$serial->deviceClose();
		}catch(Exception $e){
			$serial->deviceClose();
			echo 'error!';
			return;
		}
		echo 'finish! success send '.$succ;
	}
	
	public function actionAdd_sms(){
		$criteria=new CDbCriteria();
		$criteria->addCondition('state=0');
		$criteria->order='name DESC';
		$driver_models=Drivers::model()->findAll($criteria);
		$model=new Sms_queue;
		if(isset($_POST['Sms_queue'])){
			$model->attributes=$_POST['Sms_queue'];
			if($model->validate()){
				$id=array();
				foreach($model->driver_id as $n=>$driver_id){
					$driver_model=Drivers::model()->findByPk($driver_id);
					$sms_model=new Sms_queue;
					$sms_model->mobile_no=$driver_model->mobile_no;
					$sms_model->receiver_name=$driver_model->name;
					$sms_model->msg=$model->msg;
					$sms_model->save();
					$id[]=$sms_model->id;
				}
				$this->redirect(array('show_sms','id'=>implode(',',$id),'ret'=>'add_sms','ok'=>'0'));
			}
		}
		$this->render('sms/add_sms',array('model'=>$model,'driver_models'=>$driver_models));
	}
	
	public function actionShow_sms(){
		$this->render('sms/show_sms',array('driver_models'=>$this->loadSms()));
	}
	
	public function actionSearch_sms(){
		$criteria=new CDbCriteria();
		$criteria->addCondition('state=0');
		$blur=true;
		if(Yii::app()->getRequest()->isPostRequest){
			if(isset($_POST['keys'])){//页面传来的搜索关键字数组
				$_GET['keys']=$_POST['keys'];
			}
		}
		if(isset($_GET['keys'])){
			if(isset($_GET['keys']['blur'])&&$_GET['keys']['blur']=='0') $blur=false;
			foreach($_GET['keys'] as $key=>$val){
				if(trim($val)=='')
					unset($_GET['keys'][$key]);
				else if($key=='s_date'){//时间查询
					$criteria->addCondition("create_time>='{$val}'");
				}
				else if($key=='e_date'){//时间查询  
					$criteria->addCondition("create_time<'".date('Y-m-d',strtotime($val." +1days"))."'");
				}
				else if($key!='blur'){//按照模糊或精确查询
					$blur?$criteria->addSearchCondition($key,$val):$criteria->addCondition("{$key}='{$val}'");
				}
			}
		}
		$model=Sms_queue::model();
		$pages=new CPagination($model->count($criteria));
		$pages->pageSize=Yii::app()->params['page_size']['sms_queue'];
		$pages->applyLimit($criteria);
		
		$sort=new CSort('Sms_queue');
		$sort->applyOrder($criteria);
    	$models=$model->findAll($criteria);
		$this->render('sms/admin_sms',array(
			'models'=>$models,
			'pages'=>$pages,
			'sort'=>$sort,
		));
	}
	
	private function loadSms($id=null){
		if(!isset($id)&&!isset($_GET['id'])) 
			throw new CHttpException(404,'The requested page does not exist.');
		$id=isset($id)?$id:$_GET['id'];
		$sql="select * from sms_queue where id in($id) order by receiver_name desc";
		$driver_models=Sms_queue::model()->findAllBySql($sql);
		return $driver_models;
	} 
}